package com.cr.bio.class2;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.Charset;

public class BIOServer {
    private static Charset charset=Charset.forName("UTF-8");

    public static void main(String[] args) {
        int port=2020;
        try(ServerSocket serverSocket=new ServerSocket(port)){
            while(true){
                //接收连接，如果没有连接建立，这里会阻塞
               Socket s=serverSocket.accept();
               new Thread(new SocketHandler(s)).start();
            }
        }catch (IOException e){
            e.printStackTrace();
        }
    }
    static class SocketHandler implements Runnable{
        Socket s;

        public SocketHandler(Socket s) {
            super();
            this.s = s;
        }

        @Override
        public void run() {
            try(BufferedReader reader=new BufferedReader(new InputStreamReader(s.getInputStream(),charset));){
                String message=null;
                while((message=reader.readLine())!=null){
                    System.out.println(message);
                }
            }catch (IOException e){
                e.printStackTrace();
            }
        }
    }
}
